package com.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.utils.JDBCUtils;

public class SharePassageDao {
	
	 //建立分享连接
    public int share(String ID,String shareTitle,String shareContent,String shareCity,int shareCost,int shareDays,String shareTime)
            throws Exception,ClassNotFoundException, IllegalAccessException,
            InstantiationException, SQLException
    {
    	Connection conn = null;
    	Statement stmt = null;
    	ResultSet rs = null;
		conn = JDBCUtils.getConnection();
		stmt = conn.createStatement();
		String sql = "SELECT * FROM customer where ID ='"+ID+"'";
		rs = stmt.executeQuery(sql);
		
		String getAuthorName;
        while(rs!=null&&rs.next()){

            getAuthorName=rs.getString("name");
            stmt.execute(sql);


            String insertSQL="INSERT INTO passage(authorID,title,passageContent,city,cost,days,authorName,passageDate) VALUES" +
                    "('" + ID + "','" + shareTitle + "','"+ shareContent + "','"+ shareCity + "','"+ shareCost + "','"+ shareDays + "','"+ getAuthorName + "','"+ shareTime + "');";

            stmt.execute(insertSQL);

            return 0;
        }
        return 1;
    }
    
    //用于返回passage的编号
    //如果返回0，发生错误
    public int returnPassageID(String shareTitle)
            throws Exception
    {
    	Connection conn = null;
    	Statement stmt = null;
    	ResultSet rs = null;
		conn = JDBCUtils.getConnection();
		stmt = conn.createStatement();
		String sql = "SELECT passageID FROM passage where title ='"+shareTitle+"'";
		rs = stmt.executeQuery(sql);
		int getPassageID = 0;
        if(rs!=null&&rs.next()){

            getPassageID=rs.getInt("passageID");
            stmt.execute(sql);
        }
        return getPassageID;
    }
    

    //查询最后一篇passage的ID
    public int searchPassageID() 
    		throws Exception,ClassNotFoundException, IllegalAccessException
            , InstantiationException, SQLException 
    {
    	Connection conn = null;
    	Statement stmt = null;
    	ResultSet rs = null;
		conn = JDBCUtils.getConnection();
		stmt = conn.createStatement();
		String sql = "SELECT passageID FROM passage ORDER BY passageID DESC LIMIT 1";
		rs = stmt.executeQuery(sql);
		
		if(rs.next()) {
            int result=rs.getInt("passageID");
            stmt.close();
            conn.close();
            return result;
        }

        else {
            stmt.close();
            conn.close();
            return 0;
        }
    	
    }

}
